package com.istock.union.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.base.serializer.JsonSerializer;
import com.istock.base.serializer.json.JsonSerializerFactory;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.filter.AuthorizationCallbackAdapter;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.security.InnerTokenService;
import com.istock.union.user.service.MenuInfoService;
import com.istock.union.user.utils.WebCommonUtils;

public class PermissionCallback extends AuthorizationCallbackAdapter {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MenuInfoService menuInfoService;
	@Autowired
	private InnerTokenService tokenService;
	
	private final String REDIRECT_URL = "pre/redirectPage";
	private final String DEPT_SELECT_URL = "s/afterLogin/showDept";
	
	@Override
	public boolean preCallback(HttpServletRequest request, HttpServletResponse response, HandlerMethod targetObj) {
		final SSOUser ssoUser = SSOClientUtils.getInstance().findCurrentUser();
		if(ssoUser.getPermissions() == null || ssoUser.getPermissions().isEmpty()) {
			//如果用户没有权限信息
			//如果用户不是管理员且没有当前登录机构,一定是存在委任信息,跳转到机构选择页面
			if(ssoUser.getCurrentDept() == null && !SSOClientUtils.getInstance().isAdmin() ) {
				logger.info("the user has more dept and roles , need dept selection");
				try {
					redirectPage(request, response, DEPT_SELECT_URL, "DEPT_SELECT", "select dept");
				}catch(Exception e) {
					logger.error("return deptSelect page exception " , e);
				}
				return false;
			}
			
			//有可能是因为用户是第一次登录,准备赋权
			List<String> permList = null;
			logger.info("ready to load user permiss======================");
			//如果是超级管理员
			if(SSOClientUtils.getInstance().isAdmin()) {
				permList = menuInfoService.findAllPerm();
			}else {
				permList = menuInfoService.findPermByCredentialId(ssoUser.getCredentialId());
			}
			
			ssoUser.getPermissions().addAll(permList);
			tokenService.saveTokenModel(ssoUser);
			
		}
		return true;
	}

	private void redirectPage(HttpServletRequest request , HttpServletResponse response , String url , String ajaxCode , String message) throws Exception {
		if(WebCommonUtils.isAjax(request)) {
			//如果当前请求是ajax
            ApiBaseResponse<Object> apiBaseResponse =
                    new ApiBaseResponse<>(RetStatusEnum.FAIL, ajaxCode, message , null);

            response.setContentType("application/json");
            JsonSerializer serializer = JsonSerializerFactory.findSerializer();
            response.getWriter().println(serializer.serialize(apiBaseResponse));
            response.getWriter().flush();
		}else {
			/*View view = resolver.resolveViewName(REDIRECT_URL, request.getLocale());
			Map<String , Object> paramMap = new HashMap<String , Object>();
			paramMap.put("targetUrl", WebCommonUtils.generateTargetUrl(request.getContextPath(), url));
			view.render(paramMap, request, response);*/
			String targetUrl = WebCommonUtils.generateTargetUrl(request.getContextPath() , REDIRECT_URL);
			targetUrl = WebCommonUtils.generateFromUrl(targetUrl, "targetUrl", WebCommonUtils.generateTargetUrl(request.getContextPath(), url));
			response.sendRedirect(targetUrl);
		}
	}
}
